<template>
<d2-container>
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
           style="width: 30%;">
    <el-form-item label="产品类名称" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="所需原料类" prop="material">
      <el-select v-model="ruleForm.material" multiple placeholder="请选择">
        <el-option
          v-for="item in ruleForm.material_category"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="ruleForm.remark"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>

</d2-container>
</template>

<script>
const axios = require('axios');
import {request} from "@/network/request";

export default {
  name: 'create',
  data() {
    return {
      ruleForm: {
        name: '',
        remark: '无',
        material_category:null,
        material:null
      },
      rules: {
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'}
        ],
        material: [
          {required: true, message: '请输入所需原料', trigger: 'blur'}
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      let _this = this;
      let material = this.ruleForm.material[0];
      for (let i = 1; i < this.ruleForm.material.length; i++) {
        material += "," + this.ruleForm.material[i];
      }
      request({
          url: 'productCategory/add',
          method: 'post',
          params: {
            name: _this.ruleForm.name,
            material: material,
            remark: _this.ruleForm.remark
          }
        },
        res => {

          alert("添加成功！");
          console.log(res);
        },
        err => {
          alert("添加失败，请重试！");
          console.log(err);
        }
      );
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {
    let _this = this;
    //原材料分类
    request({
        url: 'materialCategory/query',
        params: {
          key: '',
          pages: '1',
          num: 100
        },
      },
      res => {
        console.log(res.data.records.length);
        _this.ruleForm.material_category = [];
        for (let i = 0; i < res.data.records.length; i++) {
          _this.ruleForm.material_category[i] = {};
          _this.ruleForm.material_category[i].label = res.data.records[i].name;
          _this.ruleForm.material_category[i].value = res.data.records[i].id;
        }
        console.log(_this.ruleForm.material_category);
      },
      err => {
        console.log(err);
      });
  }
}
</script>
